import { useState, useEffect } from 'react';
import { Statistic, Typography, Select, Row, Col, Card, Button, Spin, message } from 'antd';
import ReactECharts from 'echarts-for-react';
import { useNavigate } from 'react-router-dom';
import { registerMap } from 'echarts/core';
import * as echarts from 'echarts/core';
import { LineChart, PieChart, MapChart } from 'echarts/charts';
import 'echarts-wordcloud';
import china from 'echarts/map/json/china.json';
import guangdong from 'echarts/map/json/province/guangdong.json';

import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    VisualMapComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

import { getTpostsTrendData, getTpostsContentTypeData, getTpostsGeoDistribution } from '@/api/manage';

// // 注册地图数据
registerMap('china', china);
registerMap('guangdong', guangdong);

// 注册必须组件
echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    VisualMapComponent,
    LineChart,
    PieChart,
    CanvasRenderer,
    MapChart,
]);

const { Option } = Select;
const { Text } = Typography;

// 折线图配置
const lineOptions = {
    title: { text: '内容发布趋势', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
        type: 'category',
        data: [],
    },
    yAxis: { type: 'value' },
    series: [
        {
            data: [],
            type: 'line',
            smooth: true,
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(58,77,233,0.8)' },
                    { offset: 1, color: 'rgba(58,77,233,0.3)' },
                ]),
            },
        },
    ],
};

// 饼图配置
const pieOptions = {
    tooltip: { trigger: 'item' },
    legend: { orient: 'vertical', left: 'left' },
    series: [
        {
            type: 'pie',
            radius: '50%',
            data: [
                { value: 1048, name: '文章' },
                { value: 735, name: '视频' },
                { value: 580, name: '图片' },
            ],
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)',
                },
            },
        },
    ],
};

// 词云配置
const wordCloudOptions = {
    series: [
        {
            type: 'wordCloud',
            shape: 'rect', // 改为矩形基础布局
            sizeRange: [12, 60], // 缩小字号范围
            rotationRange: [0, 45], // 限制旋转角度范围
            gridSize: 10, // 增大网格间距避免重叠
            width: '100%', // 确保容器宽度
            height: '100%', // 确保容器高度
            drawOutOfBound: false,
            textStyle: {
                fontFamily: 'Microsoft YaHei',
                fontWeight: 'bold', // 增加字体加粗
                color: () =>
                    `rgba(${Math.round(Math.random() * 150)},${Math.round(Math.random() * 150)},${Math.round(
                        Math.random() * 150
                    )},0.9)`, // 增加透明度
            },
            // 添加悬停效果
            emphasis: {
                focus: 'self',
                textStyle: {
                    shadowBlur: 10,
                    shadowColor: 'rgba(0, 0, 0, 0.5)',
                },
            },
            data: [],
        },
    ],
};
const mapOptions = {
    title: { text: '地域分布', left: 'center' },
    tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}',
    },
    visualMap: {
        min: 0,
        max: 1000,
        left: 'right',
        text: ['高', '低'],
        calculable: true,
        inRange: {
            color: ['#e6f7ff', '#1890ff'],
        },
    },
    series: [
        {
            type: 'map',
            map: 'china',
            roam: true,
            emphasis: {
                label: { show: true },
            },
            data: [
                { name: '北京', value: 1000 },
                { name: '广东', value: 800 },
                { name: '浙江', value: 600 },
            ],
            markPoint: {
                symbol: 'image://https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/svgs/solid/map-pin.svg', // 使用在线图标
                symbolSize: [30, 30], // 图标尺寸
                label: {
                    show: true,
                    position: 'bottom', // 标签显示在图标下方
                    color: '#1890ff',
                    fontSize: 12,
                },
                itemStyle: {
                    color: 'transparent', // 隐藏默认圆形
                },
                data: [
                    {
                        name: '北京',
                        coord: [116.405285, 39.904989],
                        symbol: 'image:///assets/map-pin.png', // 本地图片路径（需要放在public目录）
                        symbolSize: [40, 40],
                    },
                    {
                        name: '西安',
                        coord: [108.948024, 34.263161],
                        symbolOffset: [0, -15], // 图标位置微调
                    },
                ],
            },
        },
    ],
};
//   const mapOptionsGuangdong = {
//     title: { text: '广东省分布', left: 'center' },
//     tooltip: { trigger: 'item' },
//     visualMap: {
//       min: 0,
//       max: 800,
//       left: 'right',
//       calculable: true,
//       inRange: { color: ['#e6f7ff', '#3C6256'] }
//     },
//     series: [{
//       type: 'map',
//       map: 'guangdong',
//       roam: true,
//       data: [
//         { name: '广州市', value: 800 },
//         { name: '深圳市', value: 700 }
//       ]
//     }]
// };
const mapOptionsGuangdong = (maxValue) => ({
    title: { text: '广东省分布', left: 'center' },
    tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}篇',
    },
    visualMap: {
        min: 0,
        max: maxValue,
        left: 'right',
        calculable: true,
        inRange: {
            color: ['#e6f7ff', '#3C6256'],
        },
    },
    series: [
        {
            type: 'map',
            map: 'guangdong',
            roam: true,
            data: [], // 数据在 generateOptions 中动态设置
        },
    ],
});

export default function AdminDashboard() {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(true);
    const [timeRange, setTimeRange] = useState('7days');
    const [chartData, setChartData] = useState({
        line: { sevenDays: [], thirtyDays: [] },
        pie: [],
        wordCloud: [],
        mapGD: [],
    });
    const generateWeekData = () => {
        return Array.from({ length: 7 }, (_, i) => ({
            date: `第${i + 1}天`,
            value: Math.floor(Math.random() * 200) + 50,
        }));
    };

    const generateMonthData = () => {
        return Array.from({ length: 30 }, (_, i) => ({
            date: `第${i + 1}天`,
            value: Math.floor(Math.random() * 300) + 100,
        }));
    };
    // 动态配置生成器
    const generateOptions = () => {
        const currentLineData = chartData.line[timeRange === '7days' ? 'sevenDays' : 'thirtyDays'] || [];
        const currentMapData = chartData.mapGD || [];
        const maxGDValue = Math.max(...chartData.mapGD?.map((item) => item.value), 1);
        return {
            line: {
                ...lineOptions,
                xAxis: {
                    type: 'category',
                    data: currentLineData.map((item) => new Date(item.date).toLocaleDateString()),
                },
                series: [
                    {
                        ...lineOptions.series[0],
                        data: currentLineData.map((item) => item.value),
                    },
                ],
            },
            // pie: {
            //   ...pieOptions,
            //   series: [{
            //     ...pieOptions.series[0],
            //     data: chartData.pie.map(item => ({
            //       name: item.tagName,  // 根据接口返回字段调整
            //       value: item.postCount
            //     }))
            //   }]
            // },
            wordCloud: {
                ...wordCloudOptions,
                series: [
                    {
                        ...wordCloudOptions.series[0],
                        data: chartData.wordCloud.map((item) => ({
                            // 使用内容类型接口数据
                            name: item.name,
                            value: item.value,
                            textStyle: {
                                color: `rgb(${Math.random() * 155 + 100},${Math.random() * 155 + 100},${Math.random() * 155 + 100})`,
                            },
                        })),
                    },
                ],
            },
            mapGD: {
                ...mapOptionsGuangdong(Math.max(...currentMapData.map((item) => item?.value || 0), 1)),
                series: [
                    {
                        ...mapOptionsGuangdong().series[0],
                        data: currentMapData,
                    },
                ],
            },
        };
    };

    useEffect(() => {
        const fetchData = async () => {
            try {
                setLoading(true);

                const [trendRes, contentRes, geoRes] = await Promise.all([
                    getTpostsTrendData(),
                    getTpostsContentTypeData(),
                    getTpostsGeoDistribution(),
                ]);

                setChartData({
                    line: {
                        sevenDays: trendRes.data.last7Days?.map((item) => ({
                            date: item.date,
                            value: item.count,
                        })),
                        thirtyDays: trendRes.data.last30Days?.map((item) => ({
                            date: item.date,
                            value: item.count,
                        })),
                    },
                    wordCloud: contentRes.data,
                    mapGD: geoRes.data,
                });
            } catch (error) {
                message.error('数据加载失败');
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, []);

    const handleTimeChange = (value) => {
        setTimeRange(value);
    };

    return (
        <Spin spinning={loading}>
            <div style={{ padding: 24 }}>
                {/* 核心数据图表 */}
                <Card
                    style={{ marginTop: 16 }}
                    extra={
                        <Select defaultValue="7days" size="small" onChange={handleTimeChange}>
                            <Option value="7days">最近7天</Option>
                            <Option value="30days">最近30天</Option>
                        </Select>
                    }
                >
                    <ReactECharts option={generateOptions().line} style={{ height: 400 }} />
                </Card>

                {/* 内容类型分布 */}
                <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
                    {/* <Col span={12}>
          <Card title="内容类型分布">
            <ReactECharts 
              option={generateOptions().pie} 
              style={{ height: 400 }}
            />
          </Card>
        </Col> */}
                    <Col span={12}>
                        <Card title="热门标签分布">
                            <ReactECharts option={generateOptions().wordCloud} style={{ height: 400 }} />
                        </Card>
                    </Col>
                    <Col span={12}>
                        <Card title="广东省分布">
                            <ReactECharts option={generateOptions().mapGD} style={{ height: 400 }} />
                        </Card>
                    </Col>
                </Row>
            </div>
        </Spin>
    );
}
